﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver.Builders;
using MongoDB.Bson;

namespace MongoServices
{
	/// <summary>
	/// The base &quot;Read/Write&quot; repository.
	/// </summary>
	/// <typeparam name="T">The MongoServices model to be used by this repository.</typeparam>
	public abstract class ReadWriteRepository<T> : ReadOnlyRepository<T>, IReadWriteRepository<T>
		where T : MongoServicesModel
	{
		#region Public Methods
		/// <summary>
		/// Saves the <see cref="MongoServicesModel"/>.
		/// </summary>
		/// <param name="model">The <see cref="MongoServicesModel"/> to be saved.</param>
		public virtual void Save(T model)
		{
			if (model.MarkedForDelete)
			{
				DeleteById(model.Id);
			}
			else
			{
				if (model.DateCreated == default(DateTime))
				{
					model.DateCreated = DateTime.Now;
				}

				model.DateModified = DateTime.Now;

				Collection.Save(model);
			}
		}

		/// <summary>
		/// Deleted one document from the mongoDB collection.
		/// </summary>
		/// <param name="id">The &quot;Id&quot; of the document to be deleted.</param>
		public void DeleteById(ObjectId id)
		{
			Collection.Remove(Query.EQ("_id", id));
		}
		#endregion
	}
}
